from collections import OrderedDict
from rest_framework.serializers import ModelSerializer, Serializer, CharField, FileField, PrimaryKeyRelatedField
from drf_spectacular.utils import extend_schema_field
from drf_spectacular.types import OpenApiTypes
from user.serializers import AuditSerializerMixin
from .models import Repository, Task


class NonRequiredMixin:
    def get_fields(self):
        fields = OrderedDict()
        for name, field in super().get_fields().items():
            field.required = False
            fields[name] = field
        return fields


@extend_schema_field(field=OpenApiTypes.BINARY)
class BinaryFileField(FileField):
    pass

class RepositorySerializer(AuditSerializerMixin, ModelSerializer):

    class Meta:
        model = Repository
        fields = '__all__'


class RepositoryMutationSerializer(NonRequiredMixin, RepositorySerializer):
    class Meta:
        model = Repository
        fields = '__all__'


class ExecuteSerializer(ModelSerializer):
    repository = PrimaryKeyRelatedField(required=True, queryset=Repository.objects.all())
    playbook = CharField(default='site.yml')

    class Meta:
        model = Task
        fields = ['repository', 'playbook']


class TaskSerializer(AuditSerializerMixin, ModelSerializer):
    repository = RepositorySerializer()

    class Meta:
        model = Task
        fields = '__all__'

class TaskSummarySerializer(AuditSerializerMixin, ModelSerializer):
    repository = RepositorySerializer()

    class Meta:
        model = Task
        exclude = ['output']